import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_pink_app/business/cancel_like.dart';
import 'package:flutter_pink_app/business/set_like.dart';
import 'package:mobx/mobx.dart';
import '../serialized/recommend.dart';
import "../business/get_detail_list.dart";
import '../composables/video_player.dart';
import '../composables/video_detail.dart';
import "../reactive/video_page_state.dart";
import "../storage/video_page_provider.dart";
import "package:flutter_pink_app/business/set_favourite.dart";
import "package:flutter_pink_app/business/cancel_favourite.dart";

// 视频播放页组件
class BiliVideoPage extends StatefulWidget {
  final VideoInfo _info;
  const BiliVideoPage(this._info, {Key key}) : super(key: key);

  @override
  _BiliVideoPageState createState() => _BiliVideoPageState();
}

class _BiliVideoPageState extends State<BiliVideoPage> {
  // 初始化影片详情页的响应式状态
  VideoPageHoistedState reactiveState = VideoPageHoistedState();
  ReactionDisposer isFavouriteDisposer;
  ReactionDisposer isLikeDisposer;

  // 开始生命周期
  @override
  void initState() {
    super.initState();
    _initRequst();
    // 是否收藏改变副作用
    isFavouriteDisposer = reaction(
        (_) => reactiveState.detailIsFavorite, favouriteStatusChangeRequest);
    isLikeDisposer =
        reaction((_) => reactiveState.detailisLike, likeStatusChangeRequest);
  }

  // 废弃生命周期
  @override
  void dispose() {
    print('销毁video_page');
    if (isFavouriteDisposer != null) isFavouriteDisposer();
    if (isLikeDisposer != null) isLikeDisposer();
    super.dispose();
  }

  // 初始化请求
  void _initRequst() async {
    final res = await getDetailList(widget._info.vid);
    if (res == null) {
      Timer(Duration(seconds: 5), _initRequst);
      return;
    }
    // 请求到数据后，如果页面仍挂载且则更新状态
    if (mounted) {
      reactiveState.setUpDetail(res);
      // 请求到新数据之后重新构造子树
      setState(() {});
    }
  }

  // 点赞状态改变请求
  Future<void> likeStatusChangeRequest(bool value) async {
    final String infoId = widget._info.vid;
    final requestMethod = value ? setLike : cancelLike;
    final res = await requestMethod(infoId);
    if (res.data == false) {
      print("点赞状态改变的请求失败。");
    }
  }

  // 收藏状态改变请求
  Future<void> favouriteStatusChangeRequest(bool value) async {
    final String infoId = widget._info.vid;
    final requestMethod = value ? setFavourite : cancelFavourite;
    final res = await requestMethod(infoId);
    if (res.data == false) {
      print("收藏状态改变的请求失败。");
    }
  }

  @override
  Widget build(BuildContext videoPageCtx) {
    return VideoPageProvider(
      reactiveState: reactiveState,
      child: Scaffold(
        body: Column(children: <Widget>[
          VideoPlayer(widget._info.url, widget._info.cover),
          Expanded(child: VideoDetail(['简介', '评论'], widget._info)),
        ]),
      ),
    );
  }
}
